package com.lightsaber.trade.core.service.account;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.lightsaber.trade.core.dao.BaseDao;
import com.lightsaber.trade.core.dao.account.RoleDao;
import com.lightsaber.trade.core.dao.account.UserDao;
import com.lightsaber.trade.core.dao.account.UserRoleDao;
import com.lightsaber.trade.core.entity.AuditedObject;
import com.lightsaber.trade.core.entity.BaseEntity;
import com.lightsaber.trade.core.entity.account.Role;
import com.lightsaber.trade.core.entity.account.RoleType;
import com.lightsaber.trade.core.entity.account.User;
import com.lightsaber.trade.core.entity.account.UserRole;
import com.lightsaber.trade.core.entity.account.UserType;
import com.lightsaber.trade.core.service.BaseServiceImpl;

@Service
@Transactional
public class UserManager extends BaseServiceImpl<User, String> {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    protected BaseDao getDao() {
        return userDao;
    }

    public List<User> findByUserType(UserType userType) {
        return userDao.findByUserType(userType);
    }

    public Page<User> findPageByUserType(User user, UserType userType, Page<User> page) {
        return userDao.findPageByUserType(user, userType, page);
    }

    public User saveCustomer(User user) {

        if (StringUtils.isBlank(user.getId())) {

            user.setUserType(UserType.CustomerUser);
            this.save(user);

            Role role = roleDao.get(RoleType.customer.name());
            UserRole ur = new UserRole();
            ur.setUser(user);
            ur.setRole(role);
            userRoleDao.save(ur);

            return user;

        } else {

            User old = this.get(user.getId());
            BeanUtils.copyProperties(user, old, new String[] { BaseEntity.ID, BaseEntity.VERSION,
                    AuditedObject.CREATED_BY, AuditedObject.CREATED_DATE, "userType" });

            this.save(old);
            return old;
        }
    }
}
